package com.wnhz.work.yz.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.alipay.PayResult;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.ALiBean;
import com.wnhz.work.yz.bean.Finish1;
import com.wnhz.work.yz.bean.WeiXinPayBean;
import com.wnhz.work.yz.utils.AlbumImagePath;
import com.wnhz.work.yz.utils.BitnapUtils;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.ShowAlertDialog;
import com.wnhz.work.yz.view.SkillBookPop;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class YuShouGotoPayActivity extends Activity implements View.OnClickListener {

    private LinearLayout ll_xianxia_pay;
    private List<String> imgUrl = new ArrayList<>();
    private TextView tv_pay_money;

    private TextView ali_pay_info, yue_pay_info, wx_pay_info;
    private ImageView xianxia_img, ali_img, yue_img, wx_img;
    private RecyclerView tianjia;
    private ImageView add_img;
    private TextView tv_finish;
    private String pay_money, budget_no, wallet, type;
    private boolean isCanPay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yu_shou_goto_pay);
        initData();
        initView();
    }

    private void initData() {
        pay_money = getIntent().getStringExtra("pay_money");
        budget_no = getIntent().getStringExtra("budget_no");
        wallet = getIntent().getStringExtra("wallet");

        Log.e("钱包余额 wallet ==== ", wallet + "===需支付=== " + pay_money);
        if (Double.parseDouble(wallet) > Double.parseDouble(pay_money)) {
            isCanPay = true;
        } else {
            isCanPay = false;
        }
        type = getIntent().getStringExtra("type");
    }

    private void initView() {
        ll_xianxia_pay = (LinearLayout) findViewById(R.id.ll_xianxia_pay);
        tianjia = (RecyclerView) findViewById(R.id.tianjia);
        tianjia.setLayoutManager(new GridLayoutManager(this, 4, LinearLayoutManager.VERTICAL, false));
        myadapter2 = new Myadapter2(this, imgUrl);
        tianjia.setAdapter(myadapter2);
        add_img = (ImageView) findViewById(R.id.add_img);
        add_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopmenu(v);
            }
        });
        findViewById(R.id.tv_finish).setOnClickListener(this);

        findViewById(R.id.ll_ali).setOnClickListener(this);
        findViewById(R.id.ll_wx).setOnClickListener(this);
        findViewById(R.id.ll_xianxia).setOnClickListener(this);
        findViewById(R.id.ll_yue).setOnClickListener(this);

        findViewById(R.id.submit_all).setOnClickListener(this);

        xianxia_img = (ImageView) findViewById(R.id.xianxia_img);
        ali_img = (ImageView) findViewById(R.id.ali_img);
        yue_img = (ImageView) findViewById(R.id.yue_img);
        wx_img = (ImageView) findViewById(R.id.wx_img);

        tv_pay_money = (TextView) findViewById(R.id.pay_money);
        tv_pay_money.setText("￥" + pay_money);
        ali_pay_info = (TextView) findViewById(R.id.ali_pay_info);
        yue_pay_info = (TextView) findViewById(R.id.yue_pay_info);
        wx_pay_info = (TextView) findViewById(R.id.wx_pay_info);

        if (isCanPay) {
            String str = "(需支付<font color=\"#ff0000\">" + pay_money + "</font>元)";
            yue_pay_info.setText(Html.fromHtml(str));
            pay_type = 0;
        } else {
            pay_type = -1;
            yue_pay_info.setText("(余额不足请充值\t剩余" + wallet + "元)");
        }
        String ALI_str = "(支付宝支付<font color=\"#ff0000\">" + pay_money + "</font>元)";
        ali_pay_info.setText(Html.fromHtml(ALI_str));

        String wx_str = "(微信支付<font color=\"#ff0000\">" + pay_money + "</font>元)";
        wx_pay_info.setText(Html.fromHtml(wx_str));
    }


    private int pay_type = 0;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_finish:
                finish();
                break;
            case R.id.ll_yue:
                if (isCanPay) {
                    pay_type = 0;
                } else {
                    pay_type = -1;
                }
                wx_img.setImageResource(R.mipmap.ic_choose_nor);
                yue_img.setImageResource(R.mipmap.ic_choose_li);
                ali_img.setImageResource(R.mipmap.ic_choose_nor);
                xianxia_img.setImageResource(R.mipmap.ic_choose_nor);
                ll_xianxia_pay.setVisibility(View.GONE);
                break;
            case R.id.ll_ali:
                wx_img.setImageResource(R.mipmap.ic_choose_nor);
                yue_img.setImageResource(R.mipmap.ic_choose_nor);
                ali_img.setImageResource(R.mipmap.ic_choose_li);
                xianxia_img.setImageResource(R.mipmap.ic_choose_nor);
                pay_type = 1;
                ll_xianxia_pay.setVisibility(View.GONE);
                break;
            case R.id.ll_wx:
                wx_img.setImageResource(R.mipmap.ic_choose_li);
                yue_img.setImageResource(R.mipmap.ic_choose_nor);
                ali_img.setImageResource(R.mipmap.ic_choose_nor);
                xianxia_img.setImageResource(R.mipmap.ic_choose_nor);
                pay_type = 3;
                ll_xianxia_pay.setVisibility(View.GONE);
                break;
            case R.id.ll_xianxia:
                wx_img.setImageResource(R.mipmap.ic_choose_nor);
                yue_img.setImageResource(R.mipmap.ic_choose_nor);
                ali_img.setImageResource(R.mipmap.ic_choose_nor);
                xianxia_img.setImageResource(R.mipmap.ic_choose_li);
                pay_type = 2;
                ll_xianxia_pay.setVisibility(View.VISIBLE);
                break;
            case R.id.submit_all:
                switch (pay_type) {
                    case -1:
                        MyToast("余额不足");
                        break;
                    case 0:
                        submitPay(pay_type);
                        break;
                    case 1:
                        submitPay(pay_type);
                        break;
                    case 2:
                        submitPay(pay_type);
                        break;
                    case 3:
                        submitPay(pay_type);
                        break;
                }
                break;
        }
    }

    private static final int TOALIPAY = 3;
    private static final int SDK_PAY_FLAG = 1;

    private void submitPay(final int pay_type) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("type", type);
        map.put("budget_no", budget_no);
//        map.put("token", "f2d2e75c1d9753218952a4f7ee0e49342");
//        map.put("type", "2");
//        map.put("budget_no", "20170502190548848");
        String url = "";
        switch (pay_type) {
            case 0:
                url = Url.BOOKINGPAY_WALLETPAY;
                break;
            case 1:
                url = Url.BOOKINGPAY_ALIPAY;
                break;
            case 2:
                for (int i = 0; i < imgUrl.size(); i++) {
                    String targetPath = imgUrl.get(i);
                    //调用压缩图片的方法，返回压缩后的图片path
                    String compressImage = BitnapUtils.compressImage(targetPath, targetPath, 30);
                    File compressedPic = new File(compressImage);
                    map.put("pic" + i, compressedPic);
                    Log.e("-----", compressedPic + "----" + compressImage);
                }
                url = Url.BOOKINGPAY_OFFLINEPAY;
                break;
            case 3:
                url = Url.BOOKINGPAY_WXPAY;
                break;
        }


        showDialog();
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----" + key, ":" + value + "\n");
            }
        }
        XUtil.Post(url, map, new MyCallBack<String>() {
            private Gson gson;

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        switch (pay_type) {
                            case 0:
                            case 2:
                                setStart(budget_no, pay_money, pay_type);
                                JSONObject infos = new JSONObject(info);
                                String msg = infos.optString("msg");
                                MyToast(msg);
                                EventBus.getDefault().post(new Finish1());
                                finish();
                                break;
                            case 1:
                                Log.e("==支付宝支付===", result);
                                gson = new Gson();
                                ALiBean bean = gson.fromJson(result, ALiBean.class);
                                if ("1".equals(bean.getResult())) {
                                    Message msg2 = Message.obtain();
                                    msg2.what = TOALIPAY;
                                    msg2.obj = bean.getInfo();
                                    mHandler.sendMessage(msg2);
                                }
                                break;
                            case 3:
                                Log.e("==微信支付===", result);
                                gson = new Gson();
                                WeiXinPayBean weiXinPayBean = new WeiXinPayBean();
                                weiXinPayBean = gson.fromJson(result, WeiXinPayBean.class);
                                final IWXAPI msgApi = WXAPIFactory.createWXAPI(YuShouGotoPayActivity.this, null);
                                msgApi.registerApp(MyApplication.getInstance().WXAPP_ID);
                                PayReq req = new PayReq();

                                req.appId = weiXinPayBean.getAppid();
                                req.partnerId = weiXinPayBean.getPartnerid();
                                req.prepayId = weiXinPayBean.getPrepayid();
                                req.nonceStr = weiXinPayBean.getNoncestr();
                                req.timeStamp = weiXinPayBean.getTimestamp() + "";
                                req.packageValue = "Sign=WXPay";

                                req.sign = weiXinPayBean.getSign();
                                MyApplication.getInstance().api.sendReq(req);
                                break;
                        }
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });


    }

    private void setStart(String str_number, String price, int pay_type) {
        if (pay_type == 2) {
            return;
        }
        Intent intent = new Intent(this, PaySuccessActivity.class);
        //   Log.e("----",infos.optString("order_no"));
        intent.putExtra("str_number", str_number);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
        intent.putExtra("str_tiem", df.format(new Date()));
        intent.putExtra("str_price", price);
        startActivity(intent);
    }

    private Toast toast;

    public void MyToast(String s) {
        if (toast == null)
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        else
            toast.setText(s);
        toast.show();
    }

    protected Dialog dialog;

    public void showDialog() {
        if (null == dialog) {
            dialog = ShowAlertDialog.loadingDialog(this);
        }
        dialog.show();
    }

    public void closeDialog() {
        if (null != dialog) {
            dialog.dismiss();
        }
    }

    public void payV2(ALiBean.InfoEntity info) {
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        final String orderinfo = "_input_charset=\"" + info.get_input_charset() + "\"&body=\"" + info.getBody() + "\"&notify_url=\"" + info.getNotify_url() + "\"&out_trade_no=\"" + info.getOut_trade_no() + "\"&partner=\"" + info.getPartner() + "\"&payment_type=\"" + info.getPayment_type() + "\"&seller_id=\"" + info.getSeller_id() + "\"&service=\"" + info.getService() + "\"&subject=\"" + info.getSubject() + "\"&total_fee=\"" + info.getTotal_fee() + "\"&sign=\"" + info.getSign() + "\"&sign_type=\"" + info.getSign_type() + "\"";

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(YuShouGotoPayActivity.this);
                Map<String, String> result = alipay.payV2(orderinfo, true);
                Log.i("msp", result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //   Log.e("-----", resultInfo + "---" + resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(YuShouGotoPayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        setStart(budget_no, pay_money, pay_type);
//                        MyApplication.getInstance().destoryActivity("all_yushou");
//                        MyApplication.getInstance().destoryActivity("yushoudetails");
//                        MyApplication.getInstance().destoryActivity("yushoupay");
                        EventBus.getDefault().post(new Finish1());
                        finish();

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(YuShouGotoPayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                case TOALIPAY: {
                    ALiBean.InfoEntity obj = (ALiBean.InfoEntity) msg.obj;
                    payV2(obj);
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };


    private WindowManager.LayoutParams lp;
    private SkillBookPop menuWindow;
    private final int FROM_CAMERA_CODE = 111;// 调用相机更改背景图片的请求code
    private final int FROM_ALBUM_CODE = 112;// 调用相册更改背景图片的请求code

    public void showPopmenu(View v) {
        menuWindow = new SkillBookPop(this, menuItemsOnClick);
        menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });

        menuWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        lp = getWindow().getAttributes();
        // lp.alpha = 0.6f;
        getWindow().setAttributes(lp);

    }

    private Myadapter2 myadapter2;

    class Myadapter2 extends BaseRVAdapter {

        /**
         * 构造器
         *
         * @param context 上下文
         * @param list    数据集合
         */
        public Myadapter2(Context context, @NonNull List list) {
            super(context, list);
        }

        @Override
        public int getLayoutId(int viewType) {
            return R.layout.dialog_add_tupian;
        }

        @Override
        public void onBind(BaseViewHolder holder, final int position) {
            x.image().bind(holder.getImageView(R.id.add_tu), imgUrl.get(position));
            holder.getView(R.id.delete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    imgUrl.remove(position);
                    Myadapter2.this.notifyDataSetChanged();
                    add_img.setVisibility(View.VISIBLE);
                }
            });
        }
    }

    private String imageName = "";
    /**
     * 弹出pop的菜单点击事件
     */
    private View.OnClickListener menuItemsOnClick = new View.OnClickListener() {
        Intent intent = null;


        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.from_camera2:

                    intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    // 判断存储卡是否可以用，可用进行存储
                    if (hasSdcard()) {
                        String time = System.currentTimeMillis() + "";
                        imageName = time + ".jpg";
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName)));
                    }
                    startActivityForResult(intent, FROM_CAMERA_CODE);

                    break;
                case R.id.from_album2:
                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, FROM_ALBUM_CODE);
                    break;

                default:
                    break;
            }
        }
    };

    public void showDialogv7(String title, DialogInterface.OnClickListener clickListener) {
        /***
         这里使用了 android.support.v7.app.AlertDialog.Builder
         可以直接在头部写 import android.support.v7.app.AlertDialog
         那么下面就可以写成 AlertDialog.Builder
         */
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setMessage(title);
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", clickListener);
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            //相册
            case FROM_ALBUM_CODE:
                Bitmap bm = null;
                ContentResolver resolver = getContentResolver();

                if (null != data) {
                    Uri uri = data.getData();
                    String imagePath = AlbumImagePath.getPath(this, uri);
                    updateImage(imagePath, uri);

                }
                break;
            //拍照
            case FROM_CAMERA_CODE:
                boolean hasSdcard = hasSdcard();
                if (hasSdcard) {
                    File tempFile = new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName);
                    Uri uri = Uri.fromFile(tempFile);

                    String imagePath = tempFile.getAbsolutePath();
                    System.out.println("拍照的路径=====：" + imagePath);

                    File file = new File(imagePath);
                    if (!file.exists()) {
                        return;
                    }
                    updateImage(imagePath, uri);
                } else {
                    MyToast("未找到存储卡，无法存储照片！");
                }
                break;

        }
    }

    private void updateImage(String imagePath, Uri uri) {
        if (null == imagePath) {
            return;
        }


        if (imgUrl.size() < 4) {
            imgUrl.add(imagePath);
            myadapter2.notifyDataSetChanged();
        }
        if (imgUrl.size() >= 4) {
            add_img.setVisibility(View.GONE);
        } else {
            add_img.setVisibility(View.VISIBLE);
        }
        Log.e("img", imgUrl.size() + "");
    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
}
